package impl

import (
	"context"
	"net/http"
	"time"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/hertz-contrib/sse"
	"hertz-nbdemo/biz/service"
)

var _ service.SseService = &SseServiceImpl{}

type SseServiceImpl struct {
	BaseService
}

func NewSseService() service.SseService {
	return &SseServiceImpl{}
}

func (self *SseServiceImpl) TestSse(ctx context.Context, c *app.RequestContext) {
	// client can tell server last event it received with Last-Event-ID header
	lastEventID := sse.GetLastEventID(c)
	hlog.CtxInfof(ctx, "last event ID: %s", lastEventID)

	// you must set status code and response headers before first render call
	c.SetStatusCode(http.StatusOK)
	s := sse.NewStream(c)
	for t := range time.NewTicker(1 * time.Second).C {
		event := &sse.Event{
			Event: "timestamp",
			Data:  []byte(t.Format(time.RFC3339)),
		}
		err := s.Publish(event)
		if err != nil {
			return
		}
	}
}
